#include <msp430x16x.h>

/*
  comsInit() initialises the USART
  comsSend(unsigned char c) sends the data packet c
  comsReceive() returns receieved data packet
*/

void comsInit(void)
{
  /* Set P3.6/P3.7 as transmit/receive pins */
  P3SEL |=  0xC0; /* P3.6/P6.7 to TXD data out / RXD data in */
  P3DIR |=  0x40; /* P3.6 to output */
  P3DIR &= ~0x80; /* P3.7 to input */

  /* Set P6.6 low to enable transceiver interface */
  P6SEL &= ~0x40; /* P6.6 to 3.3V I/O */
  P6DIR |=  0x40; /* P6.6 to output */
  P6OUT &= ~0x40; /* P6.6 to 0 */

  /* Set P4.6 low to enable +5V_SW power */
  P4SEL &= ~0x40; /* P4.6 to 3.3V I/O */
  P4DIR |=  0x40; /* P4.6 to output */
  P4OUT &= ~0x40; /* P4.6 to 0 */

  /* Initialise USART1 settings */
  U1CTL = (CHAR | SWRST | MM); /* Set SWRST, CHAR = 8 bit char length, MM = Address-Bit multiprocessor format */
  U1TCTL = (SSEL1); /* Use SMCLK for BRCLK source */
  U1BR0 = 0x6D; /* Baud Rate - Suggested by baud rate table for 9600Bd with 1,048,576 Hz SMCLK crystal */
  U1BR1 = 0x00; /* Baud Rate - Suggested by baud rate table for 9600Bd with 1,048,576 Hz SMCLK crystal */
  U1MCTL = 0x03; /* Modulation control - Suggested by baud rate table for 9600Bd with 1,048,576 Hz SMCLK crystal */
  ME2 |= (UTXE1 | URXE1); /* Enables USART1 transmit/receive modules */
  U1CTL &= ~SWRST; /* Clear SWRST */
  IE2 |= (UTXIE1 | URXIE1); /* Enables UTXIFG1 and URXIFG1 interrupts */
}

void comsSend(unsigned char c)
{
  IFG2 &= ~UTXIFG1; /* Disable transmit interrupt flag */
  TXBUF1 = c; /* Sends char c */
  while ((IFG2 & UTXIFG1) == 0) { } /* Don't send next command until complete flag */
}

unsigned char comsReceive(void)
{
  unsigned char rec;
  IFG2 &= ~URXIFG1; /* Disable receive interrupt flag */
  while ((IFG2 & URXIFG1) == 0) { } /* Don't read until complete flag */
  rec = U1RXBUF; /* Read received character */
  return (rec);
}

int main()
{
  comsInit();
  P1DIR=255;
  P1OUT=0;

  while (1)
  {
    comsSend(0xAA); /* Sends 10101010 */
    P1OUT=255-P1OUT; /* Oscillate port 1 for testing */
  }
    
  return 0;
}
